package top.kaoshanji.p1ch07a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * 代码清单-p1ch07a-224页a：点击次数的会话跟踪
 * URL访问地址：/sessionTracker
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 19:19
 */
public class SessionTracker extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        // 取得当前会话对象，必要时生成一个
        HttpSession session = req.getSession();

        // 为该网页增加点击数。这个值被存在 "tracker.count" 的客户端会话中
        Integer count = (Integer) session.getAttribute("tracker.count");
        if (count == null) {
            count = new Integer(1);
        } else {
            count = new Integer(count.intValue() + 1);
        }

        session.setAttribute("tracker.count", count);

        out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
        out.println("<BODY><H1>Session Tracking Demo</H1>");

        // 显示该页的点击数
        out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

        out.println("<P>");

        out.println("<H2>Here is your session data:</H2>");
        Enumeration<String> enumeration = session.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            out.println(name + ": " + session.getAttribute(name) + "<BR>");
        }

        out.println("</BODY></HTML>");

    }

}
